package com.jh.paymentchannel.service;

import com.jh.paymentchannel.business.BranchbankBussiness;
import com.jh.paymentchannel.business.TopupPayChannelBusiness;
import com.jh.paymentchannel.pojo.MiLianRegister;
import com.jh.paymentchannel.util.Util;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.net.URI;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

@Service
public class MiLianTopupRequest implements TopupRequest{
    private static final Logger log = LoggerFactory.getLogger(MiLianTopupRequest.class);

    @Value("${payment.ipAddress}")
    private String ipAddress;

    @Autowired
    private TopupPayChannelBusiness topupPayChannelBusiness;

    @Autowired
    private Util util;

    @Autowired
    private BranchbankBussiness branchbankBussiness;

    @Override
    public Map<String, String> topupRequest(HttpServletRequest request, String amount, String ordercode, String orderdesc, String extra, String notifyurl, String returnurl, String channelParam) throws Exception {
        log.info("调用米联通道开始");
        Map<String, String> map = new HashMap<String, String>();
        RestTemplate restTemplate = new RestTemplate();
        URI uri = util.getServiceUrl("transactionclear", "error url request!");
        String url = uri.toString() + "/v1.0/transactionclear/payment/query/ordercode";
        MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
        requestEntity.add("order_code", ordercode);
        String result = restTemplate.postForObject(url, requestEntity, String.class);
        log.info("查询订单信息结果result={}" + result);
        JSONObject jsonObject;
        JSONObject resultObj;
        try {
            jsonObject = JSONObject.fromObject(result);
            resultObj = jsonObject.getJSONObject("result");
        } catch (Exception e) {
            log.error("查询订单信息出错");
            map.put("resp_code", "failed");
            map.put("channel_type", "milian");
            map.put("resp_message", "没有该订单信息");
            return map;
        }
        String userid = resultObj.getString("userid");
        // 费率
        String rate = resultObj.getString("rate");
        // 额外费率
        String extraFee = resultObj.getString("extraFee");
        // 银行卡
        String bankCard = resultObj.getString("bankcard");

        restTemplate = new RestTemplate();
        uri = util.getServiceUrl("user", "error url request!");
        url = uri.toString() + "/v1.0/user/bank/default/userid";
        requestEntity = new LinkedMultiValueMap<String, String>();
        requestEntity.add("user_id", userid);
        result = restTemplate.postForObject(url, requestEntity, String.class);

        log.info("查询默认结算卡信息返回result={}" + result);
        try {
            jsonObject = JSONObject.fromObject(result);
            resultObj = jsonObject.getJSONObject("result");
        } catch (Exception e) {
            log.error("查询默认结算卡出错");
            map.put("resp_code", "failed");
            map.put("channel_type", "milian");
            map.put("resp_message", "查询默认结算卡有误");
            return map;
        }

        if (resultObj.isNullObject()) {
            map.put("resp_code", "failed");
            map.put("channel_type", "milian");
            map.put("resp_message", "没有结算卡");
            return map;
        }

        String cardNo = resultObj.getString("cardNo");
        String userName = resultObj.getString("userName");
        /** 身份证号 */
        String idcard = resultObj.getString("idcard");
        String phone = resultObj.getString("phone");
        // 开户行所在省
        String provinceOfBank = resultObj.getString("province");

        System.out.println("provinceOfBank" + provinceOfBank);
        // 开户行所在市
        String cityOfBank = resultObj.getString("city");

        System.out.println("cityOfBank" + cityOfBank);
        // 银行名称
        String bankName = resultObj.getString("bankName");
        // 支行名称
        String bankBranchName = resultObj.getString("bankBranchName");

        String cardType = resultObj.getString("cardType");

        String bankBranchNo;
        try {
            log.info("查询支行联行号");
            bankBranchNo = branchbankBussiness.getNumByName(bankBranchName);
        } catch (Exception e1) {
            log.info("查询支行联行号有误");
            map.put("resp_code", "failed");
            map.put("channel_type", "milian");
            map.put("resp_message", "查询支行联行号有误");
            return map;
        }

        log.info("查询支行联行号结果返回bankBranchNo={}",bankBranchNo);

        restTemplate = new RestTemplate();
        uri = util.getServiceUrl("user", "error url request!");
        url = uri.toString() + "/v1.0/user/bank/default/cardno";
        requestEntity = new LinkedMultiValueMap<String, String>();
        requestEntity.add("cardno", bankCard);
        requestEntity.add("type", "0");
        result = restTemplate.postForObject(url, requestEntity, String.class);
        log.info("查询银行卡信息返回result={}" + result);
        try {
            jsonObject = JSONObject.fromObject(result);
            resultObj = jsonObject.getJSONObject("result");
        } catch (Exception e) {
            log.error("查询银行卡信息出错");
            map.put("resp_code", "failed");
            map.put("channel_type", "milian");
            map.put("resp_message", "查询银行卡信息有误");
            return map;
        }


        String cardName = resultObj.getString("bankName");
        String expiredTime = resultObj.getString("expiredTime");

        String securityCode = resultObj.getString("securityCode");

        String cardtype = resultObj.getString("cardType");

        String bankname = Util.queryBankNameByBranchName(bankName);
        String cardname = Util.queryBankNameByBranchName(cardName);

        MiLianRegister miLianRegister;

        try {
            miLianRegister = topupPayChannelBusiness.getMiLianRegister(Long.parseLong(userid));
        } catch (Exception e) {
            log.info("查询用户进件信息有误==-==" + e.getMessage());
            map.put("resp_code", "failed");
            map.put("channel_type", "milian");
            map.put("resp_message", "查询用户进件信息有误");
            return map;
        }

        if (provinceOfBank == null || "".equals(provinceOfBank) || "null".equals(provinceOfBank)) {
            provinceOfBank = "";
        }

        if (cityOfBank == null || "".equals(cityOfBank) || "null".equals(cityOfBank)) {
            cityOfBank = "";
        }

        if (bankBranchNo == null || "".equals(bankBranchNo) || "".equals(bankBranchNo)) {
            bankBranchNo = "";
        }

        if (bankBranchName == null || "".equals(bankBranchName) || "null".equals(bankBranchName)) {
            bankBranchName = "";
        }

        if (expiredTime == null || "".equals(expiredTime) || "null".equals(expiredTime)) {
            expiredTime = "";
        }

        if (securityCode == null || "".equals(securityCode) || "null".equals(securityCode)) {
            securityCode = "";
        }

        if (miLianRegister == null) {
            log.info("用户需要进件========");
            // cjRegister为空表示用户需要进件
            Map<String,String> maps = new HashMap<String, String>();
            maps.put("resp_code", "success");
            maps.put("channel_type", "milian");
            maps.put("redirect_url",
                    ipAddress + "/v1.0/paymentchannel/topup/tomilianquickbankinfo?bankName="
                            + URLEncoder.encode(bankname, "UTF-8") + "&bankBranchId=" + bankBranchNo + "&bankNo="
                            + cardNo + "&bankCard=" + bankCard + "&cardName=" + URLEncoder.encode(cardname, "UTF-8")
                            + "&amount=" + amount + "&ordercode=" + ordercode + "&provinceOfBank="
                            + URLEncoder.encode(provinceOfBank, "UTF-8") + "&cityOfBank="
                            + URLEncoder.encode(cityOfBank, "UTF-8") + "&bankBranchName="
                            + URLEncoder.encode(bankBranchName, "UTF-8") + "&cardType="
                            + URLEncoder.encode(cardType, "UTF-8") + "&cardtype=" + URLEncoder.encode(cardtype, "UTF-8")
                            + "&expiredTime=" + expiredTime + "&securityCode=" + securityCode + "&isRegister=0");
            return maps;
        }

//        miLianRegister = topupPayChannelBusiness.getMiLianRegister(Long.valueOf(userid), rate);

        restTemplate = new RestTemplate();
        uri = util.getServiceUrl("user", "error url request!");
        url = uri.toString() + "/v1.0/user/bank/default/userid";
        requestEntity = new LinkedMultiValueMap<String, String>();
        requestEntity.add("user_id", userid);
        result = restTemplate.postForObject(url, requestEntity, String.class);

        log.info("查询默认结算卡RESULT================" + result);
        try {

            jsonObject = JSONObject.fromObject(result);
            resultObj = jsonObject.getJSONObject("result");
        } catch (Exception e) {
            log.error("查询默认结算卡出错");
            map.put("resp_code", "failed");
            map.put("channel_type", "jf");
            map.put("resp_message", "查询默认结算卡有误");
            return map;
        }

        if (resultObj.isNullObject()) {

            map.put("resp_code", "failed");
            map.put("channel_type", "jf");
            map.put("resp_message", "没有结算卡");
            return map;
        }

        String defaulBankCard = resultObj.getString("cardNo");

        if(!miLianRegister.getDebitRate().equals(rate) || !miLianRegister.getCountFee().equals(extraFee) || !defaulBankCard.equalsIgnoreCase(miLianRegister.getBankCard())){
            Map<String,String> maps = new HashMap<String, String>();
            log.info("用户需要重新进件========");
            maps.put("resp_code", "success");
            maps.put("channel_type", "milian");
            maps.put("redirect_url",
                    ipAddress + "/v1.0/paymentchannel/topup/tomilianquickbankinfo?bankName="
                            + URLEncoder.encode(bankname, "UTF-8") + "&bankBranchId=" + bankBranchNo + "&bankNo="
                            + cardNo + "&bankCard=" + bankCard + "&cardName=" + URLEncoder.encode(cardname, "UTF-8")
                            + "&amount=" + amount + "&ordercode=" + ordercode + "&provinceOfBank="
                            + URLEncoder.encode(provinceOfBank, "UTF-8") + "&cityOfBank="
                            + URLEncoder.encode(cityOfBank, "UTF-8") + "&bankBranchName="
                            + URLEncoder.encode(bankBranchName, "UTF-8") + "&cardType="
                            + URLEncoder.encode(cardType, "UTF-8") + "&cardtype=" + URLEncoder.encode(cardtype, "UTF-8")
                            + "&expiredTime=" + expiredTime + "&securityCode=" + securityCode + "&isRegister=3");
            return maps; // :5556
        }else{
            Map<String,String> maps = new HashMap<String, String>();
            log.info("用户不需要重新进件========");
            maps.put("resp_code", "success");
            maps.put("channel_type", "milian");
            maps.put("redirect_url",
                    ipAddress + "/v1.0/paymentchannel/topup/tomilianquickbankinfo?bankName="
                            + URLEncoder.encode(bankname, "UTF-8") + "&bankBranchId=" + bankBranchNo + "&bankNo="
                            + cardNo + "&bankCard=" + bankCard + "&cardName=" + URLEncoder.encode(cardname, "UTF-8")
                            + "&amount=" + amount + "&ordercode=" + ordercode + "&provinceOfBank="
                            + URLEncoder.encode(provinceOfBank, "UTF-8") + "&cityOfBank="
                            + URLEncoder.encode(cityOfBank, "UTF-8") + "&bankBranchName="
                            + URLEncoder.encode(bankBranchName, "UTF-8") + "&cardType="
                            + URLEncoder.encode(cardType, "UTF-8") + "&cardtype=" + URLEncoder.encode(cardtype, "UTF-8")
                            + "&expiredTime=" + expiredTime + "&securityCode=" + securityCode + "&isRegister=2");
            return maps;
        }

    }
}
